package community.hospital.interceptor;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import community.hospital.annotation.NeedPermission;
import community.hospital.common.CustomerException;
import community.hospital.common.LoginUserHolder;
import community.hospital.entity.Menu;
import community.hospital.entity.response.UserResponse;
import community.hospital.enums.BusinessEnum;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Collectors;

import static community.hospital.enums.BusinessEnum.NOT_PERMISSION;
import static community.hospital.enums.BusinessEnum.UNKNOWN_EXCEPTION;

/**
 * @Author：ydj
 * @Date：2023/1/19 23:50
 */
@Component
public class NeedPermissionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        NeedPermission annotation = handlerMethod.getMethodAnnotation(NeedPermission.class);
        if (annotation == null||!annotation.value()) {
            return true;
        }
        String[] permission = annotation.permission();
        String[] role = annotation.role();
        UserResponse user = LoginUserHolder.getUser();
        if (user == null) {
            throw new CustomerException(UNKNOWN_EXCEPTION);
        }
        if (ArrayUtil.contains(role, user.getRoleCode())
                || CollUtil.containsAny(user.getMenuKey(), Arrays.asList(permission) )) {
            return true;
        }
        throw new CustomerException(NOT_PERMISSION);
    }


}
